package com.mdinfo.base.advice;

import com.alibaba.fastjson.JSON;
import com.mdinfo.base.annotation.CCAuth;
import com.mdinfo.base.common.bean.MemberInfo;
import com.mdinfo.base.common.bean.Ref;
import com.mdinfo.base.utils.SystemUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/12/6.
 * 基于注解 CCAuth 的AOP拦截
 * 用来验证当前用户是否有对应的权限
 */
@Service
@Order(1)
@Aspect
public class AuthAdvice {

    @Around(value = "@annotation(auth)")
    public Object execute(ProceedingJoinPoint pjp, CCAuth auth)throws Throwable{

        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        CCAuth annotation = method.getAnnotation(CCAuth.class);
        System.out.println(JSON.toJSONString(annotation));

        MemberInfo info = SystemUtil.getInfo();
        String[] menuTags = auth.value();

        boolean t = true;
        for(String tag : menuTags){
            boolean temp = false;
            for(MemberInfo.MenuVo menu : info.getMenuList()){
                if(menu.getMenuTag().equals(tag)){
                    temp = true;
                    break;
                }
            }
            //temp还是false,表示该次循环中的tag没有找到
            if(!temp){
                t = false;
                break;
            }
        }
        //全部正确.执行方法
        if(t){
           return  pjp.proceed();
        }
        //没有全部匹配,返回没有权限
        else{
            return Ref.noAuthError();
        }
    }
}
